import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Avatar, List, Badge, message, Progress, Card } from 'antd';
import { 
  UserOutlined, 
  ShoppingOutlined, 
  HeartOutlined, 
  HistoryOutlined,
  SettingOutlined,
  LogoutOutlined,
  RightOutlined,
  GiftOutlined,
  CrownOutlined,
  StarFilled,
  SafetyOutlined,
  CustomerServiceOutlined,
  EnvironmentOutlined
} from '@ant-design/icons';
import { isUserAuthenticated, getUserInfo, removeUserToken } from '../../utils/auth';
import { getOrders, getFavorites, getBrowseHistory } from '../../utils/storage';

const MobileProfile = () => {
  const navigate = useNavigate();
  const isLoggedIn = isUserAuthenticated();
  const userInfo = getUserInfo();
  const orders = getOrders();
  const favorites = getFavorites();
  const browseHistory = getBrowseHistory();
  // 获取售后数据
  const afterSales = JSON.parse(localStorage.getItem('afterSales') || '[]');
  // 添加状态管理
  const [isSettingActive, setIsSettingActive] = useState(false);

  const handleLogin = () => {
    navigate('/app/login');
  };

  const handleLogout = () => {
    removeUserToken();
    message.success('已退出登录');
    navigate('/app/login');
  };

  // 点击设置按钮的处理函数
  const handleSettingClick = () => {
    setIsSettingActive(!isSettingActive);
  };

  const orderCounts = {
    pending: orders.filter(o => o.status === 'pending').length,
    paid: orders.filter(o => o.status === 'paid').length,
    shipped: orders.filter(o => o.status === 'shipped').length,
    delivered: orders.filter(o => o.status === 'delivered').length,
    refund: orders.filter(o => o.status === 'refund').length,
    aftersales: afterSales.length  // 添加售后数量
  };

  // 计算会员信息
  const getMemberInfo = () => {
    if (!userInfo) return { level: '普通会员', points: 0, nextLevel: '银牌会员', needPoints: 1000 };
    
    const points = userInfo.points || 0;
    let level = '普通会员';
    let nextLevel = '银牌会员';
    let needPoints = 1000;
    let progress = 0;
    let levelColor = '#d9d9d9';
    
    if (points >= 5000) {
      level = 'VIP';
      nextLevel = 'VIP';
      needPoints = 0;
      progress = 100;
      levelColor = '#faad14';
    } else if (points >= 3000) {
      level = '金牌会员';
      nextLevel = 'VIP';
      needPoints = 5000 - points;
      progress = ((points - 3000) / 2000) * 100;
      levelColor = '#faad14';
    } else if (points >= 1000) {
      level = '银牌会员';
      nextLevel = '金牌会员';
      needPoints = 3000 - points;
      progress = ((points - 1000) / 2000) * 100;
      levelColor = '#bfbfbf';
    } else {
      level = '普通会员';
      nextLevel = '银牌会员';
      needPoints = 1000 - points;
      progress = (points / 1000) * 100;
      levelColor = '#d46b08';
    }
    
    return { level, points, nextLevel, needPoints, progress, levelColor };
  };

  const memberInfo = getMemberInfo();

  const quickActions = [
    {
      icon: '📦',
      title: '全部订单',
      subtitle: `${orders.length}个订单`,
      onClick: () => navigate('/app/orders')
    },
    {
      icon: '📍',
      title: '收货地址',
      subtitle: '管理收货地址',
      onClick: () => navigate('/app/address')
    },
    {
      icon: '❤️',
      title: '商品收藏',
      subtitle: `${favorites.length}个商品`,
      onClick: () => navigate('/app/favorites')
    },
    {
      icon: '👀',
      title: '浏览历史',
      subtitle: `${browseHistory.length}个足迹`,
      onClick: () => navigate('/app/history')
    },
    {
      icon: '💰',
      title: '积分中心',
      subtitle: `${userInfo?.points || 0}积分 (¥${((userInfo?.points || 0) * 0.01).toFixed(2)})`,
      onClick: () => navigate('/app/points')
    }
  ];

  const serviceItems = [
    {
      title: '芭芭农场',
      icon: '🌾',
      color: '#52c41a'
    },
    {
      title: '金币618',
      icon: '🪙',
      color: '#faad14'
    },
    {
      title: '红包签到',
      icon: '🧧',
      color: '#ff4d4f'
    },
    {
      title: '游戏中心',
      icon: '🎮',
      color: '#1890ff'
    },
    {
      title: '连连消',
      icon: '🎲',
      color: '#722ed1'
    },
    {
      title: '试用领取',
      icon: '📱',
      color: '#eb2f96'
    }
  ];

  if (!isLoggedIn) {
    return (
      <div className="profile-login-prompt">
        <div className="login-prompt-content">
          <Avatar size={80} icon={<UserOutlined />} className="prompt-avatar" />
          <div className="prompt-title">欢迎来到商城</div>
          <div className="prompt-subtitle">发现更多精彩商品</div>
          <Button 
            type="primary" 
            size="large"
            onClick={handleLogin}
            className="login-prompt-btn"
          >
            立即登录
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="profile-container">
      {/* 用户信息头部 */}
      <div className="profile-header">
        <div className="user-basic-info">
          <Avatar 
            size={60} 
            src={userInfo?.avatar}
            icon={<UserOutlined />}
            className="user-avatar"
          />
          <div className="user-details">
            <div className="user-name">
              {userInfo?.nickname || userInfo?.username}
            </div>
            <div className="user-id">用户_{userInfo?.id || '557955517'}</div>
            {/* <div className="user-location">
              <EnvironmentOutlined style={{ fontSize: '12px', marginRight: '4px' }} />
              地址
            </div> */}
          </div>
          <div className="header-actions">
            <Button 
              type="text" 
              icon={<CustomerServiceOutlined />}
              className="header-action-btn"
            />
            <Button 
              type="text" 
              icon={<SettingOutlined />}
              onClick={handleSettingClick}
              className="header-action-btn"
              style={{
                transform: isSettingActive ? 'rotate(180deg)' : 'rotate(0deg)',
                transition: 'transform 0.3s'
              }}
            />
          </div>
        </div>
        {/* 退出登录按钮 */}
        {isSettingActive && (
          <div 
            style={{
              marginTop: '10px',
              padding: '8px 12px',
              background: '#f5f5f5',
              borderRadius: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              animation: 'fadeIn 0.3s'
            }}
            onClick={handleLogout}
          >
            <LogoutOutlined style={{ marginRight: '6px', color: '#ff4d4f' }} />
            <span style={{ fontWeight: '500', color: '#ff4d4f' }}>退出登录</span>
          </div>
        )}
      </div>

      {/* 会员信息卡片 */}
      <div className="member-info-section">
        <div className="member-card">
          <div className="member-header">
            <div className="member-level">
              <CrownOutlined style={{ color: memberInfo.levelColor, marginRight: '4px' }} />
              <span style={{ color: memberInfo.levelColor }}>{memberInfo.level}</span>
              {memberInfo.level === 'VIP' && (
                <div className="vip-badge">88VIP</div>
              )}
            </div>
            {memberInfo.needPoints > 0 && (
              <div className="points-tip">
                再得{memberInfo.needPoints}积分升级{memberInfo.nextLevel}
              </div>
            )}
          </div>
          
          <div className="points-section">
            <div className="points-info" style={{margin:'0px'}}>
              <div className="points-row">
                <div className="points-item" style={{display: 'block', padding: '0px'}}>
                  <div className="points-label" style={{fontSize: '16px'}}>当前会员积分:</div>
                  <div className="points-value" style={{marginLeft: '5px', fontSize: '16px', fontWeight: 'bold'}}>{memberInfo.points}</div>
                </div>
                {/* <div className="points-item"> */}
                  {/* <div className="points-label">升级条件</div>
                  <div className="points-value">
                    {memberInfo.needPoints > 0 ? `还需${memberInfo.needPoints}积分` : '已达最高等级'}
                  </div> */}
                {/* </div> */}
              </div>
            </div>
            
            {memberInfo.needPoints > 0 && (
              <div className="progress-section">
                <div className="progress-info">
                  <span>升级到{memberInfo.nextLevel}进度</span>
                </div>
                <Progress 
                  percent={memberInfo.progress} 
                  showInfo={false}
                  strokeColor={memberInfo.levelColor}
                  className="member-progress"
                />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 订单状态 */}
      <div className="order-status-section">
        <div className="section-title" style={{padding: '0px', borderBottom: '1px solid #e0e0e0', marginBottom: '10px'}}>
          <span>我的订单</span>
          <Button 
            type="link" 
            onClick={() => navigate('/app/orders')}
            className="view-all-btn"
          >
            全部 <RightOutlined />
          </Button>
        </div>
        
        <div className="order-status-grid">
          <div 
            className="order-status-item"
            style={{padding: '16px 0px 0px 0px'}}
            onClick={() => navigate('/app/orders?status=pending')}
          >
            <Badge count={orderCounts.pending} size="small">
              <div className="status-icon">💰</div>
            </Badge>
            <span className="status-text" style={{fontSize: '14px'}}>待付款</span>
          </div>
          
          <div 
            className="order-status-item"
            style={{padding: '16px 0px 0px 0px'}}
            onClick={() => navigate('/app/orders?status=paid')}
          >
            <Badge count={orderCounts.paid} size="small">
              <div className="status-icon">📦</div>
            </Badge>
            <span className="status-text" style={{fontSize: '14px'}}>待发货</span>
          </div>
          
          <div 
            className="order-status-item"
            style={{padding: '16px 0px 0px 0px'}}
            onClick={() => navigate('/app/orders?status=shipped')}
          >
            <Badge count={orderCounts.shipped} size="small">
              <div className="status-icon">🚚</div>
            </Badge>
            <span className="status-text" style={{fontSize: '14px'}}>待收货</span>
          </div>
          
          <div 
            className="order-status-item"
            style={{padding: '16px 0px 0px 0px'}}
            onClick={() => navigate('/app/orders?status=delivered')}
          >
            <Badge count={orderCounts.delivered} size="small">
              <div className="status-icon">⭐</div>
            </Badge>
            <span className="status-text" style={{fontSize: '14px'}}>待评价</span>
          </div>
          
          <div 
            className="order-status-item"
            style={{padding: '16px 0px 0px 0px'}}
            onClick={() => navigate('/app/orders?status=aftersales')}
          >
            <Badge count={orderCounts.aftersales} size="small">
              <div className="status-icon">🔄</div>
            </Badge>
            <span className="status-text" style={{fontSize: '14px'}}>退款/售后</span>
          </div>
        </div>
      </div>

      {/* 待评价订单提示 */}
      {orderCounts.delivered > 0 && (
        <div className="evaluation-reminder">
          <div className="reminder-icon">📝</div>
          <div className="reminder-text">
            许多人期待你评价 剩余 21:49:11
          </div>
          <div className="reminder-count">{orderCounts.delivered}件商品</div>
        </div>
      )}

      {/* 快捷功能 */}
      <div className="quick-actions-section">
        <div className="quick-actions-grid">
          {quickActions.map((action, index) => (
            <div 
              key={index}
              className="quick-action-item"
              onClick={action.onClick}
            >
              <div className="action-icon-large">{action.icon}</div>
              <div className="action-info">
                <div className="action-title">{action.title}</div>
                <div className="action-subtitle">{action.subtitle}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 服务工具 */}
      <div className="services-section">
        <div className="service-grid">
          {serviceItems.map((service, index) => (
            <div 
              key={index}
              className="service-item"
              onClick={() => message.info(`${service.title}功能开发中`)}
            >
              <div 
                className="service-icon"
                style={{ backgroundColor: service.color + '20' }}
              >
                {service.icon}
              </div>
              <span className="service-name">{service.title}</span>
            </div>
          ))}
        </div>
      </div>

      {/* 底部导航占位 */}
      <div style={{ height: '80px' }}></div>
    </div>
  );
};

export default MobileProfile; 